//
//  ZYOAuthViewController.swift
//  weiboZY
//
//  Created by 赵勇 on 16/5/11.
//  Copyright © 2016年 赵勇. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//https://api.weibo.com/oauth2/authorize?client_id=1716929658&redirect_uri=http://www.baidu.com
//AppSecret 1c77ac2c599ec86c63b28e0cc974518d
//code=0462ec2726c421248122cd8c108b38a2
// 新浪微博的appKey
let weiboAppKey = "1716929658"
// 新浪微博的授权回调页
let weiboRedirect_Uri = "http://www.baidu.com"
// 获取access_token的AppSecret
let weiboAppSecret = "1c77ac2c599ec86c63b28e0cc974518d"
class ZYOAuthViewController: UIViewController {

    // MARK: webView的懒加载
    private lazy var webView:UIWebView = UIWebView()

    // 自定义view
    override func loadView() {
        webView.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
     // 请求登录地址 url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(weiboAppKey)&redirect_uri=\(weiboRedirect_Uri)"
        
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        // 请求数据
        webView.loadRequest(request)
        
//        print(url)
        
        setupNavUI()
       
    }
    private func setupNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancleAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", fontSize: 15, target: self, action: "autoAction")
        
        navigationItem.title = "微博登录"
    }
    
    @objc private func cancleAction() {
//        print("cancleAction")
        dismissViewControllerAnimated(true, completion: nil)
    }
  
    @objc private func autoAction() {
//         print("autoAction")
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'm18698687201@163.com'; document.getElementById('passwd').value = 'zyscy0420'")
    }
    
    
    
        // ************************* 已封装到ViewModel（始）************************
//    // 通过code获取accessToken
//    private func requestAccessToken(code:String) {
//        
//        // 网络工具类请求数据
//        ZYNetWorkTools.sharedTool.requestAccessToken(code) { (response, error) -> () in
//            
//            if error != nil {
//                print("网络请求异常")
//                return
//            }
//            // 代码执行到此，网络请求成功
//            guard let dict = response as? [String:AnyObject] else {
//                print("数据不是字典")
//                return
//            }
//            
//             //  字典存在（字典转模型）
//            let userAcount = ZYUserAcount(dict: dict)
////            print(userAcount)
//            self.requestUserInfo(userAcount)
//        }
    
           // ************************* 已封装到ViewModel（终）************************
        
        
//        let url = "https://api.weibo.com/oauth2/access_token"
//        let params = [
//           "client_id": weiboAppKey,
//           "client_secret": weiboAppSecret,
//            "grant_type": "authorization_code",
//           "code":code,
//            "redirect_uri": weiboRedirect_Uri
//        ]
//        
//        let sessionManager = AFHTTPSessionManager()
//        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        sessionManager.POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//            
//            guard let dict = response as? [String: AnyObject] else {
//                print("数据不是字典格式")
//                return
//            }
//            // 字典存在（字典转模型）
//            let userAcount = ZYUserAcount(dict: dict)
//
//            self.requestUserInfo(userAcount)
//           
//            }) { (_, error) -> Void in
//               
//            print(error)
//                
//        }
        
//    }
    
    // ************************* 已封装到ViewModel（始）************************
//    // 获取用户个人信息
//    private func requestUserInfo(userAcount:ZYUserAcount) {
//        
//         // 网络工具类请求数据
//        ZYNetWorkTools.sharedTool.requestUserInfo(userAcount) { (response, error) -> () in
//            if error != nil {
//                print("网络请求异常")
//                return
//            }
//            
//            guard let dict = response as? [String:AnyObject] else {
//                print("数据不是字典")
//                return
//            }
//            
//            // 给模型赋值
//            userAcount.name = dict["name"] as? String
//            userAcount.avatar_large = dict["avatar_large"] as? String
//            // 归档
//            userAcount.saveUserAccount()
//            
//        }
      // ************************* 已封装到ViewModel（终）************************
        
//        let url = "https://api.weibo.com/2/users/show.json"
//        let params = [
//        "access_token":userAcount.access_token!,
//        "uid":"\(userAcount.uid)"
//        ]
//        let sessionManager = AFHTTPSessionManager()
//        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        sessionManager.GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//        
//            guard let dict = response as? [String:AnyObject] else {
//                print("不是字典类型")
//                return
//            }
//            
//            // 给模型赋值
//            userAcount.name = dict["name"] as? String
//            userAcount.avatar_large = dict["avatar_large"] as? String
//            print(userAcount)
//            
//            }) { (_, error) -> Void in
//                
//                print(error)
//                
//        }
        
        
//    }

}


// webView的代理方法
extension ZYOAuthViewController: UIWebViewDelegate {
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print(request.URL?.absoluteString)
        
        guard let url = request.URL else {
            
            // 假如地址为nil 就不执行加载
            return false
            
        }
        // 取反是不是我们要的url
        if !url.absoluteString.hasPrefix(weiboRedirect_Uri) {
            
            return true
            
        }
   
        // 请求指定地址里面的参数
       print(url.query)
        
        if let query = url.query where query.hasPrefix("code=") {
        // 获取code
            let code = query.substringFromIndex("code=".endIndex)
            
//           requestAccessToken(code)
            
            // ViewModel网络请求数据
            ZYUserAccountViewModel.sharedUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
                if isSuccess {
                    print("登录成功")
                    // dismiss当前控制器
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        // 进入欢迎界面 （发布通知）
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                        
                    })

                } else {
                   SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })
            
        } else {
            
            // 取消回调页
            dismissViewControllerAnimated(true, completion: nil)
            
        }
        
        return false
        
    }
    // 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    // 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
}



